from __future__ import annotations

import json
import os
import time
from typing import Any, Dict, List, Optional

import requests


class WeChatRobot:
    def __init__(
        self,
        webhook_key: Optional[str] = None,
        corp_id: Optional[str] = None,
        corp_secret: Optional[str] = None,
    ) -> None:
        self.webhook_key = webhook_key or os.getenv("WECHAT_WEBHOOK_KEY", "")
        self.corp_id = corp_id or os.getenv("WECHAT_CORP_ID", "")
        self.corp_secret = corp_secret or os.getenv("WECHAT_CORP_SECRET", "")
        self.token: Optional[str] = None
        self.token_expires_at: float = 0
        self.webhook_url = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={self.webhook_key}"
        self.token_url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={self.corp_id}&corpsecret={self.corp_secret}"
        self.headers = {"Content-Type": "application/json"}

    def _post(self, url: str, data: Dict[str, Any]) -> Dict[str, Any]:
        response = requests.post(url, headers=self.headers, data=json.dumps(data), timeout=10)
        response.raise_for_status()
        return response.json()

    def _check_and_refresh_token(self) -> None:
        if not self.corp_id or not self.corp_secret:
            return
        if self.token is None or time.time() >= self.token_expires_at:
            response = requests.get(self.token_url, timeout=10)
            response.raise_for_status()
            data = response.json()
            if data.get("errcode") == 0:
                self.token = data.get("access_token")
                self.token_expires_at = time.time() + float(data.get("expires_in", 7200)) - 60
            else:
                raise RuntimeError(f"Error getting token: {data}")

    def send_text_message(self, content: str) -> Dict[str, Any]:
        self._check_and_refresh_token()
        message = {"msgtype": "text", "text": {"content": content}}
        return self._post(self.webhook_url, message)


